package com.jn.zhinongbao.adapter.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.supportingagriculturaltreasures.OrderActivity;
import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.adapter.OrderAdapter;
import com.example.supportingagriculturaltreasures.bean.Order;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;

import java.util.ArrayList;
import java.util.List;

public class OrderListFragment extends Fragment implements OrderAdapter.OnOrderItemClickListener {

    private static final String ARG_USER_ID = "user_id";
    private static final String ARG_STATUS = "status";

    private RecyclerView recyclerView;
    private TextView tvEmpty;
    private OrderAdapter orderAdapter;

    private DatabaseHelper databaseHelper;
    private List<Order> orderList;
    private int userId;
    private int status;

    public static OrderListFragment newInstance(int userId, int status) {
        OrderListFragment fragment = new OrderListFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_USER_ID, userId);
        args.putInt(ARG_STATUS, status);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            userId = getArguments().getInt(ARG_USER_ID);
            status = getArguments().getInt(ARG_STATUS);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_order_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        initData();
        loadOrderData();
    }

    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        tvEmpty = view.findViewById(R.id.tv_empty);

        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
    }

    private void initData() {
        databaseHelper = new DatabaseHelper(requireContext());
        orderList = new ArrayList<>();
    }

    private void loadOrderData() {
        List<Order> allOrders = databaseHelper.getOrdersByUserId(userId);
        
        if (status == OrderActivity.STATUS_ALL) {
            // 显示所有订单
            orderList.addAll(allOrders);
        } else {
            // 根据状态筛选订单
            for (Order order : allOrders) {
                if (order.getStatus() == status) {
                    orderList.add(order);
                }
            }
        }

        if (orderList.isEmpty()) {
            recyclerView.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.VISIBLE);
            tvEmpty.setText(getEmptyText());
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            tvEmpty.setVisibility(View.GONE);
            
            orderAdapter = new OrderAdapter(requireContext(), orderList, this);
            recyclerView.setAdapter(orderAdapter);
        }
    }

    private String getEmptyText() {
        switch (status) {
            case OrderActivity.STATUS_ALL:
                return "暂无订单";
            case OrderActivity.STATUS_PAID:
                return "暂无已付款订单";
            case OrderActivity.STATUS_PENDING:
                return "暂无待发货订单";
            case OrderActivity.STATUS_SHIPPED:
                return "暂无已发货订单";
            case OrderActivity.STATUS_CONFIRMED:
                return "暂无确认收货订单";
            case OrderActivity.STATUS_CANCELLED:
                return "暂无已取消订单";
            default:
                return "暂无订单";
        }
    }

    @Override
    public void onOrderClick(Order order) {
        // 可以跳转到订单详情页
        Toast.makeText(requireContext(), "点击了订单: " + order.getProductName(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onOrderStatusChange(Order order, int newStatus) {
        boolean result;
        String message;
        
        if (newStatus == -999) {
            // 删除订单
            result = databaseHelper.deleteOrder(order.getId());
            message = result ? "订单已删除" : "删除失败";
            
            if (result) {
                orderList.remove(order);
                if (orderList.isEmpty()) {
                    recyclerView.setVisibility(View.GONE);
                    tvEmpty.setVisibility(View.VISIBLE);
                    tvEmpty.setText(getEmptyText());
                }
                orderAdapter.notifyDataSetChanged();
            }
        } else {
            // 更新订单状态
            result = databaseHelper.updateOrderStatus(order.getId(), newStatus);
            message = result ? "订单状态已更新" : "更新失败";
            
            if (result) {
                order.setStatus(newStatus);
                
                // 如果状态改变后不符合当前tab的筛选条件，则移除该订单
                if (status != OrderActivity.STATUS_ALL && order.getStatus() != status) {
                    orderList.remove(order);
                    if (orderList.isEmpty()) {
                        recyclerView.setVisibility(View.GONE);
                        tvEmpty.setVisibility(View.VISIBLE);
                        tvEmpty.setText(getEmptyText());
                    }
                }
                
                orderAdapter.notifyDataSetChanged();
            }
        }
        
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }
} 